package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 校验请求是否 事先登录过
 */
@WebFilter(
        urlPatterns = "/showSchedule.html"
)
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 判断这次请求之前是否有登录过
            // 为了使用 一些方法 我们需要强转对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取 session
        HttpSession session = request.getSession();
        if (session == null || session.getAttribute("user") == null){
            // 说明这一次请求之前 是没有登录过的
            // 重定向到登录页面 让用户重新登录
            response.sendRedirect("/index.html");
        }
        else if (session.getAttribute("user") != null){
            // 说明事先有登录过 放行
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
